package com.gaofans.vertx.boot.dbutils.config;

import com.gaofans.vertx.boot.dbutils.mapper.JsonMapperLoader;
import com.gaofans.vertx.boot.dbutils.mapper.RowMapper;
import com.gaofans.vertx.boot.dbutils.mapper.domain.ResultMapper;
import com.gaofans.vertx.boot.dbutils.mapper.rows.BeanRowMapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import reactor.core.publisher.Flux;

/**
 * @author GaoFans
 */
public class RowMapperAutoConfig implements ApplicationContextAware, BeanPostProcessor {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void config(Flux<ResultMapper> mapperFlux){
        String[] beanNames = this.applicationContext.getBeanNamesForType(BeanRowMapper.class);
        mapperFlux.subscribe(resultMapper -> {
            for (String beanName : beanNames) {
                BeanRowMapper bean = this.applicationContext.getBean(beanName, BeanRowMapper.class);
                if(bean.getClass().getName().equals(resultMapper.getName())){
                    try {
                        bean.setType(Class.forName(resultMapper.getOfType()));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }
}
